// pages/temperature/temperature.js
import {
  API_TEMPERATURE_SAVEORUPDATE,
  API_TEMPERATURE_GETLIST,
  API_TOURIST_TUBNBUNDLING,
  API_WENGANYUNUSER_LIST
} from '../../api/index'

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bindFacilityData: {},
    userInfo: {}, // 微信用户数据
    temperatureData: {
      records: [],
    }, 
    firstTemperatureData: {},
    pagecurrent: 1,
    pagesize: 10,
    services: '',
    flag: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      bindFacilityData: wx.getStorageSync('bindFacilityData')
    })
    this.getTemperatureList()
  },

  onShow: function() {
    wx.setStorageSync('changeSystem', false)
  },
  onUnload: function () {
    this.onCloseBLEConnection()
  },
  startNfc () {
    const nfc = wx.getNFCAdapter({
      success () {
        Notify({
          background: '#2CD5C3',
          message: '请将设备放入NFC识别区'
        })
      },
      fail () {
        Dialog.confirm({
          title: '初始化NFC模块失败',
          showCancelButton: false,
          confirmButtonText: '知道了'
        })
      }
    })
    nfc.onDiscovered(res => {
      const aid = parseInt(ab2hex(callback.id), 16)
      console.log(aid)
      console.log(res.messages)
      if (res.messages) {
	      const nonceId = this.ab2hex(res.value)
        const tp = parseInt(String(nonceId).slice(0, 4), 16) * 0.0078125
        console.log('startNotice:', nonceId, tp.toFixed(1))
        this.onUpdateSaveor(tp.toFixed(1))
      }
    })
  },
  /**
   * 初始化蓝牙设备
   */
  initBlue() {
    if(!this.data.flag) return
    wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
      success: res => {
        console.log('----initBlue----')
        this.setData({
          flag: false,
        })
        this.connetBlue(this.data.bindFacilityData.tpcode)
      },
      fail: res => { //如果手机上的蓝牙没有打开，可以提醒用户
        Dialog.confirm({
          title: '请开启手机蓝牙功能, 以连接配件',
          showCancelButton: false,
          confirmButtonText: '知道了'
        })
      }
    })
  },
  /**
   * 获取到设备之后连接蓝牙设备
   */
  connetBlue(deviceId) {
    console.log('----connetBlue----', deviceId)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId, //设备id
      success: res => {
        console.log("连接蓝牙成功!")
        this.getServiceId()
      },
      fail: err => {
        console.log('------connetBlue------', err)
        this.setData({
          flag: true,
        })
      }
    })
  },
  getServiceId() {
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: this.data.bindFacilityData.tpcode,
      success: res => {
        var model = res.services[0]
        this.setData({
          services: model.uuid
        })
        this.getCharacteId()//6.0
      }
    })
  },
  getCharacteId() {
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: this.data.bindFacilityData.tpcode,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: this.data.services,
      success: res => {
        for (var i = 0; i < res.characteristics.length; i++) {//2个值
          var model = res.characteristics[i]
          if (model.properties.notify == true) {
            this.setData({
              notifyId: model.uuid// 监听的值
            })
            this.startNotice(model.uuid)//7.0
          }
        }
      }
    })
  },
  startNotice(uuid){
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: this.data.bindFacilityData.tpcode,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: this.data.services,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
      success: () => {
        // 设备返回的方法
        wx.onBLECharacteristicValueChange(res => {
          // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，
          //所以需要通过一个方法转换成字符串
          var nonceId = this.ab2hex(res.value)
          const tp = parseInt(String(nonceId).slice(0, 4), 16) * 0.0078125
          console.log('startNotice:', nonceId, tp.toFixed(1))
          this.onUpdateSaveor(tp.toFixed(1))
  　　　})
      }
    })
  },
  /**
  * 将字符串转换成ArrayBufer
  */
  string2buffer(str) {
    let val = ""
    if(!str) return;
    let length = str.length;
    let index = 0;
    let array = []
    while(index < length){
      array.push(str.substring(index,index+2));
      index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  },
  /**
   * 将ArrayBuffer转换成字符串
   */
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  // 解绑系统
  onUnDindSystem() {
    Dialog.confirm({
      title: '解绑提示',
      message: '将解绑该游客用户, 确认解绑?',
    })
      .then(() => {
        const params = {
          tpcode: this.data.bindFacilityData.tpcode, 
          open_id: wx.getStorageSync('openId')
        }
        API_TOURIST_TUBNBUNDLING(params).then(res => {
          if (res.code == 200) {
            wx.showToast({
              title: '解绑成功',
            })

            setTimeout(() => {
              wx.navigateBack()
            }, 2000)
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  // 修改绑定系统
  onChangeSystem() {
    const params = {
      name: this.data.bindFacilityData.username,
      idcardno: this.data.bindFacilityData.idcardno,
      againtype: '1'
    }
    API_WENGANYUNUSER_LIST(params).then(res => {
      if (res.data instanceof Array) {
        // 保存用户系统列表
        wx.setStorageSync('userSystemList', res.data)
        wx.setStorageSync('changeSystem', true)
        wx.navigateTo({
          url: '/pages/system/system',
        })
      }
    })
  },

  // 刷新当前温度
  onUpdateSaveor(tp) {
    const params = {
      name: this.data.bindFacilityData.username,
      idcardno: this.data.bindFacilityData.idcardno,
      tpcode: this.data.bindFacilityData.tpcode,
      tp,
      tourist: this.data.bindFacilityData.sort == 8 ? 'Y' : '',
      userid: this.data.bindFacilityData.userid + ''
    }
    API_TEMPERATURE_SAVEORUPDATE(params).then(res => {
      wx.showToast({
        title: '刷新温度成功',
      })
      this.onCloseBLEConnection()
      this.data.pagecurrent = 1
      this.data.temperatureData = {
        records: [{}],
      }
      this.getTemperatureList()
    })
  },

  onCloseBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.bindFacilityData.tpcode,
      success (res) {
        console.log('蓝牙已断开')
      }
    })
    wx.closeBluetoothAdapter({
      success (res) {
        console.log('蓝牙模块关闭')
      }
    })
  },

  // 获取更多
  onLoadMore() {
    this.data.pagecurrent = this.data.pagecurrent + 1
    this.getTemperatureList()
  },

  // 获取温度列表
  getTemperatureList() {
    const params = {
      name: this.data.bindFacilityData.username,
      idcardno: this.data.bindFacilityData.idcardno,
      tpcode: this.data.bindFacilityData.tpcode,
      pagesize: this.data.pagesize,
      pagecurrent: this.data.pagecurrent,
      tourist: this.data.bindFacilityData.sort == 8 ? 'Y' : '',
      userid: this.data.bindFacilityData.userid + ''
    }
    API_TEMPERATURE_GETLIST(params).then(res => {
      if (this.data.pagecurrent == 1) {
        this.setData({
          temperatureData: res.data
        })
      } else {
        this.setData({
          temperatureData: {
            ...res.data,
            records: [...this.data.temperatureData.records, ...res.data.records]
          }
        })
      }
      this.setData({
        firstTemperatureData: this.data.temperatureData.records[0] || {},
        flag: true
      })
    })
  }
})